package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private IDishService dishService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

    /**
     * 菜品条件分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){

        //1). 构造分页条件对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //2). 构建查询及排序条件
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        dlqw.like(name!=null,Dish::getName,name);
        dlqw.orderByDesc(Dish::getUpdateTime);

        //3). 执行分页条件查询
        dishService.page(pageInfo,dlqw);
        //4). 遍历分页查询列表数据，根据分类ID查询分类信息，从而获取该菜品的分类名称
        //4.1对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        //方法一:lambda表达式
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

       /* //方法二:增强for

        ArrayList<DishDto> list = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(record,dishDto);
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            list.add(dishDto);
        }
        dishDtoPage.setRecords(list);*/
        //5). 封装数据并返回
        return R.success(dishDtoPage);
    }

    /**
     * 回显数据(修改菜品)
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品和口味
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateDishDto(@RequestBody DishDto dishDto){

        // 1、修改菜品dish表的数据
        dishService.updateById(dishDto);

        //取出菜品id Long dishId = dishDto.getId();
        // 2、修改菜品的口味数据 如何完成？？
        // 2.1 先删除原有的口味数据: delete from dish_flavor where dish_id = ?;
        LambdaQueryWrapper<DishFlavor> qw =new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(qw);
        // 2.2 添加菜品口味数据 List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return R.success("修改菜品成功");
    }

    /**
     * 逻辑删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids){

        //1.根据dish_id删除口味数据
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(qw);

        //2.删除菜品数据
        dishService.removeByIds(ids);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return R.success("删除成功");
    }

    /**
     * 停售起售
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R updateStatus(@RequestParam List<Long> ids,@PathVariable Integer status){
        /*LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.in(Dish::getId, ids);
        qw.set(Dish::getStatus,status);
        dishService.update(qw);*/

        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key

        return R.success("操作成功");
    }


    //根据分类id查询菜品(用来绑定菜品分类和菜品)
    @GetMapping("/list")
    public R<List<DishDto>> selectIds(Long categoryId,Integer status){

        //存储缓存数据
        ArrayList<DishDto> dishDtoList =null;
        ArrayList<DishDto> dishDtos =new ArrayList<>();

        String key = "dish_"+categoryId+"_"+status;
        //先从redis中获取缓存数据
        dishDtoList = (ArrayList<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList!=null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(categoryId!= null,Dish::getCategoryId,categoryId);
        qw.eq(Dish::getStatus,1);
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //菜品数据集合
        //ArrayList<DishDto> dishDtos = new ArrayList<>();
        //1.新建dishDto集合
        List<Dish> list = dishService.list(qw);
        //2.遍历dish集合,把dish对象属性添加到dishDto中,再把口味数据也添加进去
        for (Dish dish : list) {
            //新建dishDto对象
            DishDto dishDto = new DishDto();
            //把dish对象属性拷贝到dishDto
            BeanUtils.copyProperties(dish,dishDto);
            //根据条件查询到dish的口味集合
            LambdaQueryWrapper<DishFlavor> fqw = new LambdaQueryWrapper<>();
            fqw.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> flavors = dishFlavorService.list(fqw);

            //把dishflavors集合传入dishDto
            dishDto.setFlavors(flavors);
            //添加dishDto
            dishDtos.add(dishDto);
        }
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }

}
